package com.nd.qa.shareplate.controller;

import java.net.InetAddress;
import java.text.SimpleDateFormat;


import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import com.nd.qa.shareplate.common.SessionUserInfo;
import com.nd.qa.shareplate.common.SysConstant;
import com.nd.qa.shareplate.model.ApkInfo;
import com.nd.qa.shareplate.service.ApkService;
import com.nd.qa.shareplate.util.JsonUtil;


/**
 * <br>apk管理类
 * @author huangjian
 * @createDate 2015-09-21 下午 18:08:08
 * @version V1.0
 */

@Controller
@RequestMapping("/apk/*")
public class APKController {

	Logger logger = LoggerFactory.getLogger(APKController.class);
	
	@Autowired
	@Qualifier("com.nd.qa.shareplate.service.ApkService")
	private ApkService apkService ;
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/totalApk")
	public String totalApk(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,Model model,HttpSession session){
		
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		if (sessionUserInfo==null) {
			return "/user/index";
		}
		String userId = sessionUserInfo.getUserId();
		HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
		ApkInfo apk = new ApkInfo();
		apk.setUserId(userId);
		Integer totalPages = 0;//总记录数
		Integer currentPage = Integer.valueOf(String.valueOf(inParam.get("currentPage")));
		Integer pageSize = Integer.valueOf(String.valueOf(inParam.get("pageSize")));
		Integer startSize = (currentPage-1)*pageSize;
		try {
			List<HashMap<String, Object>> totalApkList = apkService.queryTotalApk(apk);
			if (totalApkList.size()>0&&totalApkList.size()%pageSize==0) {
				totalPages = totalApkList.size()/pageSize;
			}else {
				totalPages = totalApkList.size()/pageSize + 1;
			}
			/*List<Apk> apkList1 = apkService.queryApkByUserId(apk);
			for (int i = 0; i < apkList1.size(); i++) {
				System.out.println(apkList1.get(i).getApkDescription());
				System.out.println(apkList1.get(i).getApkName());
				System.out.println(apkList1.get(i).getSavePath());
				System.out.println(apkList1.get(i).getUserId());
			}*/
			HashMap<String,Object> paramMap = new HashMap<String,Object>();
			paramMap.put("startSize", startSize);
			paramMap.put("pageSize", pageSize);
			paramMap.put("userId", sessionUserInfo.getUserId());
			List<HashMap<String, Object>> apkList = apkService.queryApkById(paramMap);
			model.addAttribute("apkList", apkList);
			model.addAttribute("totalPages", totalPages);
		} catch (Exception e) {
			logger.error("查询apk信息异常"+e);
			e.printStackTrace();
		}
		return "/main/apkinfo";
	}
	/**
	 * 录入apk信息
	 * @param request
	 * @param response
	 * @param params
	 * @param model
	 * @param session
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/insertApkInfo")
	public void insertApkInfo(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,Model model,HttpSession session){
		
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		if (sessionUserInfo==null) {
			resultMap.put("code", "-2");
			resultMap.put("message", "您暂未登录，请先登录");
		}
		//获取入参
		HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
		String apkName = String.valueOf(inParam.get("apkName"));
		String fileName = String.valueOf(inParam.get("fileName"));
		String version = String.valueOf(inParam.get("version"));
		String apkDesc = String.valueOf(inParam.get("apkDesc"));
		String savePath = String.valueOf(inParam.get("savePath"));
		String localApkPath = String.valueOf(inParam.get("localApkPath"));
		try {
			savePath = request.getScheme()+"://"+InetAddress.getLocalHost().getHostAddress()+":"+ request.getLocalPort()+request.getContextPath()+savePath;
			//将生成路径入库
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
			String createTime = simpleDateFormat.format(new Date());
			ApkInfo apk = new ApkInfo();
			apk.setApkDesc(apkDesc);
			apk.setApkName(apkName);
			apk.setStatus("A");
			apk.setApkVersion(version);
			apk.setApkPath(savePath);
			apk.setCreateTime(createTime);
			apk.setUserId(sessionUserInfo.getUserId());
			apk.setLocalApkPath(localApkPath);
			apkService.insertApkInfo(apk);
			resultMap.put("code", "0");
			resultMap.put("message", "录入apk信息成功");
			response.getWriter().print(JsonUtil.toString(resultMap));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 删除apk信息
	 * @param request
	 * @param response
	 * @param session
	 * @param params
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/deleteApkById")
	public void deleteApkById(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params){
		
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		if (sessionUserInfo==null) {
			resultMap.put("code", "-2");
			resultMap.put("message", "您暂未登录，请先登录");
		}
		response.setCharacterEncoding("UTF-8");
	    response.setContentType("text/html;charset=UTF-8");
	    HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
	    Integer apkId = Integer.valueOf(String.valueOf(inParam.get("apkId")));
	    ApkInfo apk = new ApkInfo();
	    apk.setApkId(apkId);
	    apk.setUserId(sessionUserInfo.getUserId());
	    try {
	    	apkService.delAPKInfo(apk);
			resultMap.put("code", "0");
			resultMap.put("message", "删除apk信息成功");
			response.getWriter().print(JsonUtil.toString(resultMap));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
